package com.knowif.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.knowif.dao.TutorInfoMapper;
import com.knowif.dao.UserOrderMapper;
import com.knowif.dao.UserOrderStatusMapper;
import com.knowif.enumInfo.UserOrderStatusEnum;
import com.knowif.pojo.TUser;
import com.knowif.pojo.Topic;
import com.knowif.pojo.TutorInfo;
import com.knowif.pojo.TutorInfoExample;
import com.knowif.pojo.UserComment;
import com.knowif.pojo.UserCommentExample;
import com.knowif.pojo.UserOrder;
import com.knowif.pojo.UserOrderExample;
import com.knowif.pojo.UserOrderStatus;
import com.knowif.system.model.RestBean;
import com.knowif.util.commonUtil.IntegerUtil;

/**
 * @author xingyao
 * @Description: 订单管理dao
 */
@Service
public class UserOrder_service {
	
	
	@Autowired
	private UserOrderMapper userOrderMapper;
	
	@Autowired
	private UserComment_service userComment_service;
	
	@Autowired
	private UserOrderStatusMapper userOrderStatusMapper;
	
	@Autowired
	private TutorInfoMapper tutorInfoMapper;

	@Autowired
	private UserOrderFlow_service userOrderFlow_service;

	@Autowired
	private UserOrderStatus_service userOrderStatus_service;
	
	@Autowired
	private User_service user_service;
	
	@Autowired
	private Topic_service topic_service;
	
	
	@Autowired
	private Tutor_service tutor_service;
	
	/**
	 * @author: xingyao
	 * @Description:  查找订单信息，包括查找已经删除的订单信息    用于管理员查找所有的订单记录
	 * @param userOrderExample
	 * @return
	 */
	public List<UserOrder> selectByExampleAndNotVirtual(UserOrderExample userOrderExample){
		if(userOrderExample != null && userOrderExample.getOredCriteria() != null && !userOrderExample.getOredCriteria().isEmpty()){
			userOrderExample.getOredCriteria().get(0).andStatusNotEqualTo(UserOrderStatusEnum.VIRTUAL.getState());
		}else{
			userOrderExample = new UserOrderExample();
			userOrderExample.createCriteria().andStatusNotEqualTo(UserOrderStatusEnum.VIRTUAL.getState());
		}
		List<UserOrder> userOrders = userOrderMapper.selectByExample(userOrderExample);
		return userOrders;
	}
	
	
	/**
	 * @author: xingyao
	 * @Description:  查找订单信息，包括查找已经删除的订单信息    用于管理员查找所有的订单记录
	 * @param userOrderExample
	 * @return
	 */
	public List<UserOrder> selectByExample(UserOrderExample userOrderExample){
		if(userOrderExample == null){
			return new ArrayList<UserOrder>();
		}
		List<UserOrder> userOrders = userOrderMapper.selectByExample(userOrderExample);
		return userOrders;
	}

	
	public List<UserOrder> getByUserOrderIds(List<Integer> userOrderIds) {
		if(userOrderIds == null || userOrderIds.isEmpty()){
			return new ArrayList<UserOrder>();
		}
		UserOrderExample userOrderExample = new UserOrderExample();
		userOrderExample.createCriteria().andIdIn(userOrderIds);
		List<UserOrder> userOrders = selectByExample(userOrderExample);
		return userOrders;
	}

	/**
	 * @author: xingyao
	 * @Description:  查找订单信息，包括查找已经删除的订单信息    用于管理员查找所有的订单记录
	 * @param userOrderExample
	 * @return
	 */
	public List<UserOrder> selectUserOrderDetail(UserOrderExample userOrderExample){
		if(userOrderExample == null){
			return null;
		}
		List<UserOrder> userOrders = selectByExampleAndNotVirtual(userOrderExample);
		List<Integer> topicIds = UserOrder.getTopicIds(userOrders);
		List<Topic> topics = topic_service.selectTopic(topicIds);
		UserOrder.addTopics(topics, userOrders);

		List<Integer> tUserIds = UserOrder.getTUserIds(userOrders);
		List<TUser> tUsers = user_service.selectByUserIds(tUserIds);
		UserOrder.addTUsers(tUsers, userOrders);


		List<Integer> userIds = UserOrder.getTutorIds(userOrders);
		List<TutorInfo> tutorInfos = tutor_service.selectByUserIds(userIds);
		UserOrder.addTutors(tutorInfos, userOrders);
		return userOrders;
	}
	
	/**
	 * @author: xingyao 
	 * @Description:  查找订单记录，用于普通用户查找自身的订单记录，不包括已经删除的订单
	 * @param userOrderExample
	 * @return
	 */
	public List<UserOrder> selectNotDeleteOrder(UserOrderExample userOrderExample){
		if(userOrderExample == null){
			return null;
		}
		userOrderExample.createCriteria().andStatusNotEqualTo(UserOrderStatusEnum.CANCEL.getState());
		List<UserOrder> userOrders = selectByExampleAndNotVirtual(userOrderExample);



		return userOrders;
	}
	
	
	/**
	 * @author: xingyao 
	 * @Description:  查询订单及其评论
	 * 
	 * @param userOrderExample
	 * @return
	 */
	public RestBean<?> selectOrderDetail(UserCommentExample userCommentExample,Integer userId){
		if(userCommentExample == null){
			return RestBean.buildError("没有找到订单信息", RestBean.not_userComment);
		}
		
		List<UserComment> userComments = userComment_service.selectUserComment(userCommentExample);
		if(userComments == null || userComments.isEmpty()){
			return RestBean.buildError("没有订单评论信息", RestBean.not_userComment);
		}
		List<UserOrder> userOrders = userComment_service.getUserComment(userId, userComments);
		return RestBean.buildSuccess(userOrders);
	}


	
	
	
	
	/**
	 * @author: xingyao 
	 * @Description: 用于查找用户订单的流水的详情
	 * @param userOrderExample
	 * @return
	 */
	public List<UserOrderStatus> selectOrderStatus(UserOrderExample userOrderExample){
		if(userOrderExample == null){
			return null;
		}
		List<UserOrder> userOrders = selectByExampleAndNotVirtual(userOrderExample);
		if(userOrders == null || userOrders.isEmpty()){
			return null;
		}
		List<UserOrderStatus> orderStatuResult = new ArrayList<UserOrderStatus>();
		List<UserOrderStatus> userOrderStatuss = userOrderStatus_service.selectByUserOrderIds(UserOrder.getUserOrderIds(userOrders));
		
		List<UserOrderStatus> result = null;
		for(UserOrder userOrder : userOrders){
			result = new ArrayList<UserOrderStatus>();
			if(userOrderStatuss != null && !userOrderStatuss.isEmpty()){
				for(UserOrderStatus userOrderStatus : userOrderStatuss){
					if(userOrder.getId() != null && userOrder.getId().equals(userOrderStatus.getUserOrderId())){
						userOrderStatus.setUserOrder(userOrder);
						result.add(userOrderStatus);
					}
				}
			}
			orderStatuResult.addAll(result);
		}
		return orderStatuResult;
	}
	
	/**
	 * @author: xingyao 
	 * @Description:  保存用户订单信息 并返回主键值,要先
	 * @param userOrder
	 * @return
	 */
	@Transactional
	public boolean saveUserOrder(UserOrder userOrder){
		if(userOrder == null){
			throw new RuntimeException("保存用户订单不能为空");
		}
		userOrderMapper.insert(userOrder);
		UserOrderStatus userOrderStatus = new UserOrderStatus();
		userOrderStatus.setUserOrderId(userOrder.getId());
		userOrderStatus.setStatus(userOrder.getStatus());
		int userOrderStatusId = userOrderStatusMapper.insert(userOrderStatus);
		if(userOrderStatusId == 0){
			throw new RuntimeException("保存用户订单状态信息错误");
		}
		return true;
	}
	
	
	/**
	 * @author: xingyao 
	 * @Description:  保存用户订单状态信息，先更新用户订单表里面的status字段，然后再向用户订单状态表插入一条最近状态记录
	 * @param userOrderStatus
	 * @return
	 */
	@Transactional
	public boolean saveUserOrderStatus(UserOrderStatus userOrderStatus){
		if(userOrderStatus == null){
			throw new RuntimeException("保存用户订单状态对象不能为空");
		}
		UserOrderExample userOrderExample = new UserOrderExample();
		userOrderExample.createCriteria().andStatusEqualTo(userOrderStatus.getStatus());
		
		//更新用户订单表中是status记录
		UserOrder userOrder = new UserOrder();
		userOrder.setId(userOrderStatus.getUserOrderId());
		userOrder.setStatus(userOrderStatus.getStatus());
		int result = userOrderMapper.updateByPrimaryKeySelective(userOrder);
		if(result == 0){
			throw new RuntimeException("更新用户订单失败");
		}
		result = userOrderStatusMapper.insert(userOrderStatus);
		if(result == 0){
			throw new RuntimeException("保存用户订单状态失败");
		}
		return true;
	}
	
	/**
	 * @author: xingyao 
	 * @Description:  对订单进行评分
	 * @param userOrder
	 * @return
	 */
	public RestBean<?> orderStar(UserOrder userOrder){
		if(userOrder == null){
			return RestBean.buildError("请输入你要评论的订单id");
		}
		//更新订单信息
		userOrderMapper.updateByPrimaryKeySelective(userOrder);
		
		
		userOrder = userOrderMapper.selectByPrimaryKey(userOrder.getId());
		
		Topic topic = topic_service.selectTopic(userOrder.getTopicId());
		if(topic != null){
			if(topic.getDealNum() != null){
				topic.setDealNum(topic.getDealNum() +1);
			}else{
				topic.setDealNum(1);
			}
			topic_service.updateTopic(topic);
		}
		
		
		TutorInfoExample table_tutorInfoExample = new TutorInfoExample();
		table_tutorInfoExample.createCriteria().andUserIdEqualTo(userOrder.getToUserId());
		
		
		List<TutorInfo> tutorInfos = tutorInfoMapper.selectByExample(table_tutorInfoExample);
		if(tutorInfos == null || tutorInfos.isEmpty()){
			return RestBean.buildError("不存在该导师");
		}
		TutorInfo tutorInfo = tutorInfos.get(0);
		
		
		UserOrderExample userOrderExample = new UserOrderExample();
		userOrderExample.createCriteria().andToUserIdEqualTo(userOrder.getToUserId());
		List<UserOrder> userOrders = selectByExample(userOrderExample);
		
		double starCount = 0;
		double totalInCome = 0;
		if(userOrders == null || userOrders.isEmpty()){
			return RestBean.buildError(RestBean.SYSTEMERROR);
		}
		for(UserOrder order : userOrders){
			if(order.getStar() == null){
				starCount += 0;
			}else{
				starCount += order.getStar();
			}
			if(order.getPrice() != null){
				totalInCome += order.getPrice();
			}
		}
		
		int userCommentNumber = userComment_service.selectNumberBytutorId(userOrder.getToUserId());
		if(userCommentNumber != 0){
			starCount = Math.round(starCount / userCommentNumber);
		}
		tutorInfo.setTotalScore(starCount);
		tutorInfo.setTotalIncome(totalInCome);
		tutorInfo.setHelpsNum(userOrders.size());
		
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andIdEqualTo(tutorInfo.getId());
		tutorInfoMapper.updateByExampleSelective(tutorInfo, tutorInfoExample);
		return RestBean.buildSuccess("添加评分成功");
	}
	
	
	/**
	 * @author: xingyao 
	 * @Description:  删除订单信息，不是真正的物理删除，是逻辑删除。管理员还是可以查询的到，用户自身看不见
	 * @param userOrderId
	 * @return
	 */
	@Transactional
	public boolean deleteUserOrder(Integer userOrderId){
		if(userOrderId == null){
			throw new RuntimeException("删除订单信息id不能为空");
		}
		UserOrder userOrder = new UserOrder();
		userOrder.setId(userOrderId);
		userOrder.setStatus(UserOrderStatusEnum.CANCEL.getState());
		int result = userOrderMapper.updateByPrimaryKeySelective(userOrder);
		if(result == 0){
			throw new RuntimeException("删除用户订单信息失败");
		}
		UserOrderStatus userOrderStatus = new UserOrderStatus();
		userOrderStatus.setUserOrderId(userOrderId);
		userOrderStatus.setStatus(UserOrderStatusEnum.CANCEL.getState());
		result = userOrderStatusMapper.updateByOrderIdSelective(userOrderStatus);
        if(result == 0){
            throw new RuntimeException("删除用户订单状态信息失败");
        }
        return true;
    }

	/**
	 * 订单筛选
	 * @param params
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
    public PageInfo<UserOrder> screen(Map<String, Object> params, int pageNumber, int pageSize) {
		PageHelper.startPage(pageNumber, pageSize);
		List<UserOrder> userOrders = userOrderMapper.screen(params);;
		fillUserOrder(userOrders);
		PageInfo<UserOrder> pageInfo = new PageInfo<UserOrder>(userOrders);
		return pageInfo;
	}

	/**
	 * 补充UserOrder信息
	 * @param userOrders
	 */
	public void fillUserOrder(List<UserOrder> userOrders){
		//话题
		List<Integer> topicIds = UserOrder.getTopicIds(userOrders);
		List<Topic> topics = topic_service.selectTopic(topicIds);
		UserOrder.addTopics(topics, userOrders);
		//用户详情
		List<Integer> tUserIds = UserOrder.getTUserIds(userOrders);
		List<TUser> tUsers = user_service.selectByUserIds(tUserIds);
		UserOrder.addTUsers(tUsers, userOrders);
		//导师详情
		List<Integer> userIds = UserOrder.getTutorIds(userOrders);
		List<TutorInfo> tutorInfos = tutor_service.selectByUserIds(userIds);
		UserOrder.addTutors(tutorInfos, userOrders);
		
		List<Integer> userOrderIds = UserOrder.getUserOrderIds(userOrders);
		UserOrder.saveUserOrderFlows(userOrders, userOrderFlow_service.selectByUserOrderIds(userOrderIds));
		UserOrder.saveUserOrderStatuss(userOrders, userOrderStatus_service.selectByUserOrderIds(userOrderIds));
	}
	
	public List<UserOrder> selectByUserIdAndState(Integer userId,Integer state) {
		if(IntegerUtil.isEmpty(userId) || IntegerUtil.isEmpty(state)){
			return new ArrayList<UserOrder>();
		}
		UserOrderExample userOrderExample = new UserOrderExample();
		userOrderExample.createCriteria().andUserIdEqualTo(userId).andStatusEqualTo(state);
		List<UserOrder> userOrders = selectByExampleAndNotVirtual(userOrderExample);
		return userOrders;
	}
}












